package com.jhf.youke.base.app.executor;

import cn.hutool.json.JSONUtil;
import com.jhf.youke.base.domain.converter.MenuConverter;
import com.jhf.youke.base.domain.model.Do.MenuDo;
import com.jhf.youke.base.domain.model.dto.MenuDto;
import com.jhf.youke.base.domain.model.vo.MenuVo;
import com.jhf.youke.base.domain.model.vo.RouterVo;
import com.jhf.youke.base.domain.service.MenuService;
import com.jhf.youke.base.domain.service.PermissionsSetService;
import com.jhf.youke.core.entity.Pagination;
import com.jhf.youke.core.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author RHJ
 * **/
@Slf4j
@Service
public class MenuAppService {

    @Resource
    private MenuService menuService;

    @Resource
    private MenuConverter menuConverter;


    @Resource
    private PermissionsSetService permissionsSetService;

    public boolean update(MenuDto dto) {
        MenuDo menuDo =  menuConverter.dto2Do(dto);
        return menuService.update(menuDo);
    }

    public boolean delete(MenuDto dto) {
        MenuDo menuDo =  menuConverter.dto2Do(dto);
        return menuService.delete(menuDo);
    }


    public boolean insert(MenuDto dto) {
        MenuDo menuDo =  menuConverter.dto2Do(dto);
        return menuService.insert(menuDo);
    }

    public Optional<MenuVo> findById(Long id) {
        return menuService.findById(id);
    }


    public boolean remove(Long id) {
        return menuService.remove(id);
    }


    public List<MenuVo> findAllMatching(MenuDto dto) {
        MenuDo menuDo =  menuConverter.dto2Do(dto);
        return menuService.findAllMatching(menuDo);
    }


    public Pagination<MenuVo> selectPage(MenuDto dto) {
        MenuDo menuDo =  menuConverter.dto2Do(dto);
        return menuService.selectPage(menuDo);
    }

    public List<RouterVo> getRouters(User user) {
        // 1.得到用户所有权限
        Set<String> permissions = user.getPermissionsMap();
        log.info("permissions {}", JSONUtil.toJsonStr(permissions));
        // 2.得到用户拥有的菜单ids
        Set<Long> menuIds = permissionsSetService.getMenuIdsByUser(permissions);
        // 3. 得到所有菜单并转为前端需要结果集
        List<RouterVo> routerVoList = menuService.getRouterList(menuIds, user.getId());
        log.info("RouterVoList {}", JSONUtil.toJsonStr(routerVoList));
        return routerVoList;
    }
}

